package com.budwk.app.sqfw.services.impl;

import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.app.sqfw.models.Sqfw_textReplace;
import com.budwk.app.sqfw.services.SqfwTextReplaceService;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;

@IocBean(args = {"refer:dao"})
public class SqfwTextReplaceServiceImpl extends BaseServiceImpl<Sqfw_textReplace> implements SqfwTextReplaceService {
    public SqfwTextReplaceServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public String replaceText(String contentStr, String sourceType) {

        if (StringUtils.isBlank(contentStr)) return null;

        // 首先按照长度进行排序按照顺序进行替换
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(sourceType)) {
            cnd.and(Sqfw_textReplace::getType, "=", sourceType);
        }
        cnd.orderBy(Sqfw_textReplace::getReplaceTextLength, "desc");
        List<Sqfw_textReplace> replaceTextList = query(cnd);

        for (Sqfw_textReplace replaceText : replaceTextList) {
            if (replaceText.getReplaceText() == null) replaceText.setReplaceText("");
            if (contentStr.contains(replaceText.getOriginalText()))
                contentStr = contentStr.replace(replaceText.getOriginalText(), replaceText.getReplaceText());
        }
        return contentStr;
    }
}
